package com.aceitunaproject.shared.serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Binary object serializer implementation that uses Java serialization
 * 
 * @author Maciej Miechowicz
 */
public class BinaryObjectSerializer implements ObjectSerializer {

	/**
	 * {@inheritDoc}
	 */
	public byte[] serialize(Object object) {
		ByteArrayOutputStream result = new ByteArrayOutputStream();

		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(result);
			out.writeObject(object);
		} catch(IOException ioe) {
			throw new RuntimeException("Error serializing object", ioe);
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch(Exception ex) {
					// ignore
				}
			}
		}

		return result.toByteArray();
	}

	/**
	 * {@inheritDoc}
	 */
	public Object deserialize(byte[] data) {
		Object result = null;

		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new ByteArrayInputStream(data));
			result = in.readObject();
		} catch(ClassNotFoundException cnfe) {
			throw new RuntimeException(cnfe);
		} catch(IOException ioe) {
			throw new RuntimeException("Error deserializing object", ioe);
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch(Exception ex) {
					// ignore
				}
			}
		}

		return result;
	}

}
